using System;
using DG.Tweening;
using Locomotion;
using TMPro;
using UnityEngine;

namespace Bubbles
{
    public class Bubble : MonoBehaviour
    {
        [SerializeField] private TextMeshPro textMesh;
        [SerializeField] private SpriteRenderer backgroundRenderer;
        [SerializeField] private BoxCollider2D boxCollider;
        [SerializeField] private BubbleAnimator bubbleAnimator;

        [SerializeField] private float backgroundPadding = 0.4f;
        
        private Animator _animator;

        
        private void Awake()
        {
            _animator = GetComponent<Animator>();
        }

        private void OnEnable()
        {
            GroundDetector.AnyCharacterGroundedChanged += GroundDetector_AnyCharacterGroundedChanged;
            boxCollider.enabled = true;
        }

        private void OnDisable()
        {
            GroundDetector.AnyCharacterGroundedChanged -= GroundDetector_AnyCharacterGroundedChanged;
            boxCollider.enabled = false;
        }

        private void Update()
        {
            UpdateSize();
        }

        public void SetText(string text)
        {
            textMesh.text = text;
        }

        public void ShowCriticalHitEffect()
        {
            _animator.Play("Hit");
        }
        
        private void GroundDetector_AnyCharacterGroundedChanged(GroundDetector.GroundChangedEventArgs groundChangedEventArgs)
        {
            if (groundChangedEventArgs.LandedCollider == boxCollider)
            {
                bubbleAnimator.OnLanded();
            }
        }

        private void UpdateSize()
        {
            float targetSizeX = textMesh.rectTransform.sizeDelta.x + 
                                backgroundPadding * 2;
            if (Mathf.Approximately(
                backgroundRenderer.size.x,
                targetSizeX))
            {
                return;
            }
            
            Vector2 size = new(
                targetSizeX,
                textMesh.rectTransform.sizeDelta.y);
            backgroundRenderer.size = size;
            boxCollider.size = size;
        }
    }
}
